package com.example.security.authentication.dao;

import com.example.security.CommonParam;
import com.example.security.auth.UserServiceImpl;
import com.example.security.auth.Users;
import com.example.security.authentication.SmsAuthenticationToken;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @className: SmsAuthenticationProvider
 * @author: YTF
 * @date: 2025/5/1 10:46
 * @description:
 */
@Component
@RequiredArgsConstructor
public class SmsAuthenticationProvider implements AuthenticationProvider {

    private final UserServiceImpl userService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String phone = (String) authentication.getPrincipal();
        String code = (String) authentication.getCredentials();

        // 明确调用手机号查询方法
        Users users = userService.getUserByPhone(phone);
        List<String> authorities = users.getAuthorities();
        // 将 List 转换为 String 数组
        String[] array = authorities.toArray(new String[0]);
        UserDetails user = User.builder()
                .username(users.getUsername())
                .password(users.getPassword())
                .roles(array)
                .build();

        // 验证验证码
        Map<String, String> captcha = CommonParam.CAPTCHA;
        if (captcha.get(phone) == null || !captcha.get(phone).equals(code)) {
            throw new BadCredentialsException("验证码错误");
        }

        return new SmsAuthenticationToken(user, null, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (SmsAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
